package com.xjt.wx_admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjt.wx_admin.entity.UserLatelyMsg;
import com.xjt.wx_admin.entity.dto.SendMsg;
import com.xjt.wx_admin.mapper.UserLatelyMsgMapper;
import com.xjt.wx_admin.service.UserLatelyMsgService;
import com.xjt.wx_admin.util.SecurityUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Xujt
 * @since 2023-03-22 11:33:28
 */
@Service
public class UserLatelyMsgServiceImpl extends ServiceImpl<UserLatelyMsgMapper, UserLatelyMsg> implements UserLatelyMsgService {


    @Override
    public List<UserLatelyMsg> queryLatelyMsg() {
        List<UserLatelyMsg> userLatelyMsgs = baseMapper.queryLatelyMsg(SecurityUtils.getUserId());
        for (UserLatelyMsg userLatelyMsg : userLatelyMsgs) {
            if (userLatelyMsg.getRemark()!=null && !userLatelyMsg.getRemark().equals("")){
                userLatelyMsg.setFriendName(userLatelyMsg.getRemark());
            }
        }
        return userLatelyMsgs;
    }


    /**
     * 更新会话消息
     *
     * @param sendMsg 更新会话消息
     */
    @Override
    public void updateSessionMsg(SendMsg sendMsg) {
//        自己的会话更新
        UserLatelyMsg myLatelyMsg = getOne(Wrappers.<UserLatelyMsg>lambdaQuery()
                .eq(UserLatelyMsg::getUserId, SecurityUtils.getUserId())
                .eq(UserLatelyMsg::getFriendId, sendMsg.getToId())
        );
        if (myLatelyMsg==null){
            myLatelyMsg = new UserLatelyMsg();
            myLatelyMsg.setMsg(sendMsg.getMsg());
            myLatelyMsg.setUserId(SecurityUtils.getUserId());
            myLatelyMsg.setUpdateTime(LocalDateTime.now());
            myLatelyMsg.setFriendId(sendMsg.getToId());
            save(myLatelyMsg);
        }else {
            myLatelyMsg.setMsg(sendMsg.getMsg());
            myLatelyMsg.setUpdateTime(LocalDateTime.now());
            updateById(myLatelyMsg);
        }
//        对方得会话更新
        UserLatelyMsg friendLatelyMsg = getOne(Wrappers.<UserLatelyMsg>lambdaQuery()
                .eq(UserLatelyMsg::getUserId, sendMsg.getToId())
                .eq(UserLatelyMsg::getFriendId, SecurityUtils.getUserId())
        );
        if (friendLatelyMsg==null){
            friendLatelyMsg = new UserLatelyMsg();
            friendLatelyMsg.setMsg(sendMsg.getMsg());
            friendLatelyMsg.setUserId(sendMsg.getToId());
            friendLatelyMsg.setUpdateTime(LocalDateTime.now());
            friendLatelyMsg.setFriendId(SecurityUtils.getUserId());
            save(friendLatelyMsg);
        }else {
            friendLatelyMsg.setMsg(sendMsg.getMsg());
            friendLatelyMsg.setUpdateTime(LocalDateTime.now());
            updateById(friendLatelyMsg);
        }

    }
}
